package com.gougou.pic.service;



import com.gougou.pic.entity.PicUploadResult;
import com.gougou.pic.util.FileUtils;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

@Service
public class TxyunPicUploadService {
    String bucketName = "gougou-1256960672";

    @Value("${upload.ROOT_PATH}")
    private  String ROOT_PATH;

    @Value("${upload.ROOT_URL}")
    public  String ROOT_URL;


    /**********************
     *
     * 先得到腾讯云对象存储客户端对象
     *
     * @return
     * ********************
     */
    public COSClient getCosClient() {
        // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials("AKIDSkroZCn5GG6lFYudO1VpBSddT8lGs5NU", "6395qTvJXjqmX7WksqfJm4DBzd6OWTNA");


        ClientConfig clientConfig = new ClientConfig(new Region("ap-chongqing"));
    // 3 生成cos客户端

        COSClient cosclient = new COSClient(cred, clientConfig);
    // bucket的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
        return cosclient;
    }


    /****************************
     *
     * 存储图片到腾讯云对象存储服务器
     *
     * 思路：
     * 传入 MultipartFile文件对象 path要想存储的根目录位置
     * 先用FileUtils.upload()方法写入到本地，然后拿到本地的file对象
     * 用客户端上传file对象
     * 删除本地file文件对象缓存
     *
     * @param uploadFile
     * @param path
     * @return
     * **************************
     */
    public PicUploadResult fileUpload(MultipartFile uploadFile, String path){

        //写入文件到本地
        String filename=uploadFile.getOriginalFilename();
        FileUtils.upload(uploadFile, this.ROOT_PATH+path,filename);
        File localFile = new File(this.ROOT_PATH+path+"/"+filename);

        //得到对象存储客户端,并上传到云对象存储
        COSClient cosClient = getCosClient();
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, path+"/"+filename,localFile);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);

        //结束：封装返回值,删除图片缓存，关闭客户端
        PicUploadResult picUploadResult = FileUtils.parsePicResult(localFile,ROOT_URL,path, filename);
        localFile.delete();
        cosClient.shutdown();

        return picUploadResult;
    }





}
